Back to Basics

R you markDown?

Daniel Chen

August 15, 2017

R Markdown

This is an R Markdown presentation. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document.

Slide with Bullets

  • Bullet 1
  • Bullet 2
  • Bullet 3

Slide with R Output

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Slide with Plot

Rstudio

Global Options

Markdown

R Markdown Cheatsheet

Help > Cheatsheets > R Markdown Cheatsheet

“Pandoc’s Markdown”

Markdown

R Markdown

Getting Started with Rmd files

Literate Programming: interweaving code, its output, and regular prose text


File > New File > R Markdown …

New Rmd File

\[\dfrac{1}{2} \alpha\]

The YAML header

---
title: 'Back to Basics'
subtitle: 'R you markDown?'
author: "Daniel Chen"
date: "June 26, 2017"
output: 
  revealjs::revealjs_presentation:
    theme: "night"
    highlight: "zenburn"
    css: styles.css
    self_contained: true
    reveal_options:
      slideNumber: true
      previewLinks: true
---

revealjs: http://rmarkdown.rstudio.com/revealjs_presentation_format.html

Output

Output Options

Main Document

R Chunks

Write:

```{r eval=TRUE}
n = 10
rnorm(n)
```

Output:

n = 10
rnorm(n)
##  [1]  0.61892480 -0.07359877 -3.12219080  0.95222673  0.48518271
##  [6] -0.52393054 -0.94141446 -1.00377148 -0.46957563  1.27972157

Prose Text

The previous slide showed random draws from the normal distribution with mean = 0 and sd = 1.

There were 10 draws.


We can either

  1. manually type in the number, n
  2. print the value of n in an r chunk.
print(n)
## [1] 10
  1. Or we can run R code inline as so: ` r n`

Chunks

```{r}
# R code here
```
```{r chunk_name}
# R code here
```
```{r chunk_name, echo = TRUE}
# R code here
```

Documented, repliciable/reproducible, and automatic

The knit button (ctrl + shift + k)

rmarkdown::render(input,
                  output_format = NULL, output_file = NULL, output_dir = NULL,
                  output_options = NULL, intermediates_dir = NULL,
                  knit_root_dir = NULL,
                  runtime = c("auto", "static", "shiny", "shiny_prerendered"),
                  clean = TRUE,
                  params = NULL,
                  knit_meta = NULL, envir = parent.frame(),
                  run_pandoc = TRUE, quiet = FALSE, encoding = getOption("encoding"))

Parameters

DEMO 01-parameters

---
title: "parameters"
author: "Daniel Chen"
date: ""
output: html_document
params:
  data: ""
---

Parameterized Reports

Run in R/Rmd:

```{r}
rmarkdown::render(input = '01-parameters/params.Rmd',
                  quiet = TRUE,
                  params = list(
                      data = 'cars'
                  ))
```

Run in the command line:

  1. install: pandoc pandoc-citeproc
  2. shell:
Rscript -e "rmarkdown::render(input = '01-parameters/params.Rmd',
                              params = list(data = 'mtcars'))"

What else?

RMarkdown Website

Notebooks

R Notebook

http://rmarkdown.rstudio.com/r_notebooks.html

  • output: html_document -> output: html_notebook
    • output visible immediately beneath the input.
    • R Markdown documen:, all the code is sent to the console at once
    • Notebook: one line at a time is sent
    • Slightly better error handling
    • “knit” vs “previewed”
    • preview does not execute any of your R code chunks
      • it simply shows you a rendered copy of the markdown in your document along with the most recent chunk output
    • .nb.html

Other Languages (SQL)

DEMO 02-notebook

library(DBI)
library(RSQLite)

rm(list = ls())

con = dbConnect(SQLite(), dbname = "data/survey.db")
```{sql connection=con}
SELECT * from Person;
```
SELECT * from Person;
5 records
id personal family
dyer William Dyer
pb Frank Pabodie
lake Anderson Lake
roe Valentina Roerich
danforth Frank Danforth

Data into R

```{sql connection=con, output.var=df_sql}
SELECT * from Person;
```

Data from R

name = 'William'
```{sql connection=con, output.var=df_sql}
SELECT * from Person WHERE personal = ?name;
```

Slides

Not much more different than r markdown/notebooks

  • html: ioslides
  • html: slidy
  • html: revealjs (install.packages('revealjs'))
  • pdf: beamer
output: 
  revealjs::revealjs_presentation

HTML works too!

Markdown documents can also render HTML!

It’s how I make a 2-column slide

.column-left2{
  float: left;
  width: 50%;
  text-align: left;
}
.column-right2{
  float: right;
  width: 50%;
  text-align: left;
}
<div class="column-left2">
  <center>
  Hello
  </center>
</div>

<div class="column-right2">
  <center>
  there!
  </center>
</div>

Interactive Documents

Intro to Shiny

DEMO 03-shiny_docs

  • Introduce the concepts of Shiny without the boilerplate
  • Minimal ui code
  • server code is not in a function

Shiny Presentations

You can also have shiny apps run in a presentation like this!

No demo though.

Dashboards

flexdashboard

http://rmarkdown.rstudio.com/flexdashboard/

  • Use R Markdown!
  • Different layouts
    • row/column
    • storyboard
    • mobile
---
title: "Row Orientation"
output: 
  flexdashboard::flex_dashboard
---

Example 1

Example 2

Example 3

Websites

blogdown

  • R Markdown and Hugo
  • devtools::install_github('rstudio/blogdown')
    • blogdown::install_hugo()
    • blogdown::new_site()
      • RStudio projects
    • blogdown::serve_site()
  • https://bookdown.org/yihui/blogdown/

Books

bookdown

Minimal Viable Product

DEMO 05-bookdown/01-minimal

---
title: "A Book"
author: "Frida Gomam"
site: bookdown::bookdown_site
documentclass: book
output:
  bookdown::gitbook: default
  bookdown::pdf_book: default
---

# Hello World

Hi.

Bye.

bookdown::render_book('index.Rmd', 'all')

rendered book will be under _book

bookdown-demo

bookdown::render_book('index.Rmd', 'all')

M-K vs K-M

  • “Merge and Knit” (M-K): default
  • “Knit and Merge” (K-M): new_session = TRUE or new_session: yes

  • K-M does not allow Rmd files to be in subdirectories, but M-K does.

Misc

Working directory

Notebooks

  • chunk is always the directory containing the notebook .Rmd file.
  • allows for same behaviour while knitting and in interactive mode
  • get a warning if you try to change the working directory inside a notebook chunk
  • revert back to the notebook’s directory once the chunk is finished executing

  • use the knitr root.dir option
    • knitr::opts_knit$set(root.dir = normalizePath(".."))
    • only applies to chunks
    • relative paths in Markdown are still relative to the notebook’s parent folder

Working directory

RMarkdown

if (interactive()){
    data_dir <- './data'
} else {
    data_dir <- '../data'
}

feedback needed: https://github.com/chendaniely/rendR

Other things to look at/consider

Thanks!

Thanks!